package cn.itcast.demo.task;

import cn.itcast.demo.lock.RedisLock;
import cn.itcast.demo.lock.SimpleRedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * @author 虎哥
 */
@Slf4j
//@Component
public class HelloJob2 {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Scheduled(cron = "0/10 * * * * ?")
    public void hello() throws InterruptedException {
        // 创建锁
        RedisLock lock = new SimpleRedisLock("lock1", redisTemplate);
        // 获取锁
        boolean isLock = lock.tryLock(50);
        if(!isLock){
            // 没有拿到锁
            log.error("获取锁失败！终止任务！");
            return;
        }
        try {
            log.warn("定时任务正在执行。。");
            Thread.sleep(1000);
        }finally {
            lock.unlock();
        }
    }
}
